package com.controller;

import com.dto.NoteCreateDTO;
import com.dto.NoteWithUserDTO;
import com.pojo.Notes;
import com.pojo.Result;
import com.service.NotesService;
import com.vo.NoteWithStatsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("api/notes")
public class NotesController {

    @Autowired
    private NotesService notesService;

    @GetMapping("/{noteId}/author")
    public Result<Integer> getAuthorIdByNoteId(
            @PathVariable("noteId") Integer noteId) {
        Integer authorId = notesService.getAuthorIdByNoteId(noteId);
        return authorId != null ?
                  Result.success(authorId):Result.error("获取失败");
    }


    @PostMapping
    public Result<Void> createNote(@RequestBody NoteCreateDTO dto) {
        return notesService.createNoteWithTags(dto);
    }

    @PutMapping("/{id}")
    public Result<Void> updateNote(@PathVariable Integer id, @RequestBody Notes note) {
        note.setId(id);
        return notesService.updateNote(note);
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteNote(@PathVariable Integer id) {
        return notesService.deleteNote(id);
    }

    @GetMapping("/{id}")
    public Result<NoteWithUserDTO> getNoteById(@PathVariable Integer id) {
        return notesService.getNoteById(id);
    }


    @GetMapping("/public-by-tag")
    public Result<List<NoteWithStatsVO>> getPublicNotesByTag(
            @RequestParam Integer tagId,
            @RequestParam(defaultValue = "10") int limit,
            @RequestParam(required = false) Integer userId) {

        if (userId == null) userId = -1;   // 未登录统一 -1
        return Result.success(notesService.getPublicNotesByTagWithStats(tagId, limit, userId));
    }


    @GetMapping("/with-stats")
    public Result<List<NoteWithStatsVO>> getRecentPublicNotesWithStats(
            @RequestParam(required = false) Integer userId,
            @RequestParam(defaultValue = "10") int limit) {
        return notesService.getRecentPublicNotesWithStats(userId, limit);
    }



    @GetMapping("/liked-by/{userId}")
    public Result<List<NoteWithStatsVO>> getLikedNotesWithStats(@PathVariable Integer userId) {
        return Result.success(notesService.getLikedNotesWithStats(userId));
    }

    @GetMapping("/collected-by/{userId}")
    public Result<List<NoteWithStatsVO>> getCollectedNotesWithStats(@PathVariable Integer userId) {
        return Result.success(notesService.getCollectedNotesWithStats(userId));
    }

    @GetMapping("/user/{userId}/with-stats")
    public Result<List<NoteWithStatsVO>> getUserNotesWithStats(
            @PathVariable Integer userId,
            @RequestParam(required = false) Integer currentUserId) {
        // 如果调用方没传，就用路径里的 userId（自己看自己）
        if (currentUserId == null) currentUserId = userId;
        return Result.success(notesService.getUserNotesWithStats(userId, currentUserId));
    }
}